<?php
// +----------------------------------------------------------------------
// | Date: 2018-05-04
// +----------------------------------------------------------------------
// | Author: zj 
// +----------------------------------------------------------------------

namespace app\game\controller;
use cmf\controller\UserBaseController;
use app\game\api\SystemApi;
use think\Db;
class GameroomController extends UserBaseController{
    public function index(){
        $p = $this->request->param('p')?:1;
        $game_id = $this->request->param('gameID');
        $serverId = $this->request->param('serverID');
        $pageSize = 10;
        if(empty($serverId)){
            $this->result([],0,'服务器ID不能为空','json',[],'status');
        }
        $web = Db::name('server')->where(['id'=>$serverId])->find();
        if(empty($web)){
            $this->result([],0,'找不到服务器信息','json',[],'status');
        }
        $sys = new SystemApi($serverId);
        
        //游戏配置
        $query = 'totalQuery';
        $game_type = 'game_type';
        if(!empty($game_id)){
            $type_data['where'] = ['game_type_tbl.game_id'=>$game_id];
        }
        $type_data['join'] = 'join game_config_tbl on game_type_tbl.game_id = game_config_tbl.game_id';
        $type_data['field'] = 'game_type_tbl.*,game_config_tbl.game_m,game_config_tbl.game_key_c';
        $type_data['limit'] = ($p-1)*$pageSize.','.$pageSize;
        $type_data['order'] = 'game_type_tbl.game_id,game_type';
        $type_data['model'] = $game_type;
        $data = $sys->getDbMes($query, $type_data);
        $total = $data['totalCount'];
        $gameRoomList = $data['result'];
        $pdata = ['list'=>$gameRoomList, 'total'=>$total];
    	$this->result($pdata,1,'请求成功','json',[], 'status');
    }
    public function delete(){
        $gameID = $this->request->param('gameID');
        $gameType = $this->request->param('gameType');
        $serverId = $this->request->param('serverID');
        if( is_null($gameID) || is_null($gameType) ){
            $this->result([],0,'gameID和gameType不能为空','json',[],'status');
        }
        if(empty($serverId)){
            $this->result([],0,'服务器ID不能为空','json',[],'status');
        }
        $web = Db::name('server')->where(['id'=>$serverId])->find();
        if(empty($web)){
            $this->result([],0,'找不到服务器信息','json',[],'status');
        }
        $game_type = 'game_type';
        $del = 'totalDel';
        $type_data['model'] = $game_type;
        $type_data['where'] = ['game_id'=>$gameID,'game_type'=>$gameType];
        $sys = new SystemApi($serverId);
        $data = $sys->getDbMes($del, $type_data);
        if($data=='ok'){
            $this->result([],1,'删除成功','json',[], 'status');
        }else{
            $this->result([],0,'删除失败','json',[], 'status');
        }
    }
    //表单
    public function update(){
    	$gameID = $this->request->param('gameID');
        $gameType = $this->request->param('gameType');
        $serverId = $this->request->param('serverID');
        if(empty($gameID)){
            $this->result([],0,'请传入gameID','json',[], 'status');
        }
         if(empty($serverId)){
            $this->result([],0,'服务器ID不能为空','json',[],'status');
        }
        $web = Db::name('server')->where(['id'=>$serverId])->find();
        if(empty($web)){
            $this->result([],0,'找不到服务器信息','json',[],'status');
        }
        $sys = new SystemApi($serverId);
        $query = 'totalQuery';
        $config_data['model'] = 'game_config';
        $config_data['where'] = ['game_id'=>$gameID];
        $cfgData = $sys->getDbMes($query, $config_data);
        if(empty($cfgData['result'])){
            $this->result([],0,'无此游戏','json',[], 'status');
        }
        //多规则group
        $multi = ['config_x'=>'3'];
        $room_type = [['value'=>0,'label'=>'普通房间'],['value'=>1,'label'=>'比赛房间'],['value'=>2,'label'=>'人满即开']];
        $match_type = [['value'=>0,'label'=>'系统防作弊'],['value'=>1,'label'=>'有空房就进入'],['value'=>2,'label'=>'有空房就进(可重复)'],['value'=>3,'label'=>'满就开']];
        $autoStart = [['value'=>0,'label'=>'手动'],['value'=>1,'label'=>'自动']];
        $type = [['value'=>-1,'label'=>'开房模式'],['value'=>0,'label'=>'0号房'],['value'=>1,'label'=>'1号房'],['value'=>2,'label'=>'2号房'],['value'=>3,'label'=>'3号房'],['value'=>4,'label'=>'4号房'],['value'=>5,'label'=>'5号房'],['value'=>6,'label'=>'6号房'],['value'=>7,'label'=>'7号房'],['value'=>8,'label'=>'8号房'],['value'=>9,'label'=>'9号房'],['value'=>10,'label'=>'10号房']];
        $roomStatus = [['value'=>1,'label'=>'活动'],['value'=>0,'label'=>'禁用']];
        $hallStatus = [['value'=>0,'label'=>'不显示在大厅'],['value'=>1,'label'=>'单独显示在大厅']];
        $formField = [
            'game_type'=>['type'=>'select','option'=>$type,'name'=>'房间号','group'=>1],
            'game_name'=>['type'=>'input','name'=>'房间名','group'=>2],
            'config_x'=>['type'=>'input','name'=>'房间配置','group'=>3,'multi'=>true],
            'gold_min_q'=>['type'=>'input','name'=>'最少积分','group'=>4],
            'gold_max_q'=>['type'=>'input','name'=>'最大积分','group'=>5],
            'room_type'=>['type'=>'select','option'=>$room_type,'name'=>'房间类型','group'=>6],
            'match_type'=>['type'=>'select','option'=>$match_type,'name'=>'匹配规则','group'=>7],
            'max_wait_time'=>['type'=>'input','name'=>'匹配时长','group'=>8],
            'realplay_n'=>['type'=>'input','name'=>'匹配真人个数','group'=>9],
            'autoStart_i'=>['type'=>'select','option'=>$autoStart,'name'=>'是否自动运行','group'=>10],
            'isactive_i'=>['type'=>'select','option'=>$roomStatus,'name'=>'房间状态','group'=>11],
            'showinhall'=>['type'=>'select','option'=>$hallStatus,'name'=>'房间状态','group'=>12]
        ];
        $modify_params = [
            'game_id'=>intval($gameID)
        ];  
        //游戏的校验项
        $configs = Db::name('gameid_config')->where(['gameid'=>$gameID])->field('configid')->select()->toArray();
        $configids = array_column($configs, 'configid');
        $configData = Db::name('config_valide')->where(['id'=>['in',$configids],'special'=>['gt',0]])->field('name_c,key_c,value_c,descr,validate,special,message')->select()->toArray();
        $modify = 0;
        if(isset($gameType) && $gameType!=''){
            $modify = 1;
        	//更新
            $room_data['model'] = 'game_type';
            $room_data['query'] = 'find';
            $room_data['where'] = ['game_id'=>$gameID,'game_type'=>$gameType];
            $rcdata = $sys->getDbMes($query, $room_data);
            $gameRoom = $rcdata['result'];
            if(empty($gameRoom)){
                 $this->result([],0,'请求失败','json',[], 'status');
            }
            $isActive = $gameRoom['isactive_i'];
            if(($isActive&1)==1){
                $gameRoom['isactive_i'] = 1;
            }
            if(($isActive&2)==2){
                $gameRoom['showinhall'] = 1;
            }
            foreach ($formField as $k => $v){
                if(array_key_exists($k,$gameRoom)){
                    $formField[$k]['value'] = array_key_exists($k, $multi)?explode(',',$gameRoom[$k] ):$gameRoom[$k];
                }
            }
            
            $modify_params['old_game_type'] = intval($gameType);
        }
        //支持多规则的格式拼接
        $valideList = array();
        foreach($configData as $k=>$v){
            $group = $v['special'];
            $multKey = array_search($group, $multi);
            if(!empty($multKey)){
                $count = isset($formField[$multKey]['childrenFormList'])?count($formField[$multKey]['childrenFormList'])+1:1;
                $formField[$multKey]['childrenFormList'][] = array('key'=> trim($v['key_c'],'-'),'group'=>$group.'-'.$count,'name'=>$v['name_c'],'type'=>'input','key_u'=>$v['key_c']);
                if($modify){
                    $value = $formField[$multKey]['value'];
                    $key = array_search($v['key_c'],$value);
                    if($key!==false){
                        $type = $this->getRuleType($v['validate']);
                        if($type!=false){
                            $formdataTot = count($formField[$multKey]['childrenFormList'])-1;
                            $formField[$multKey]['childrenFormList'][$formdataTot]['value'] = $type($value[$key+1]);
                        }
                    }
                }
                $arr = $v;
                $arr['special'] =  $group.'-'.$count;
                $valideList[$group]['special'] = $group;
                $valideList[$group]['valideList'][] = $arr;
                unset($configData[$k]);
            }
        }
        if(!empty($valideList)){
            $configData = array_merge($configData,$valideList);
        }
        $pdata = ['form_data'=>$formField,'modify_params'=>$modify_params,'valide'=>$configData];
        
        $this->result($pdata,1,'请求成功','json',[], 'status');
    }
    public function getRuleType($str) {
        if (strpos($str, 'integer') !== FALSE) {
            return 'intval';
        } elseif (strpos($str, 'string') !== FALSE) {
            return 'strval';
        } elseif (strpos($str, 'float') !== FALSE) {
            return 'floatval';
        } elseif (strpos($str, 'boolean') !== FALSE){
            return 'boolval';
        }else{
            return false;
        }
    }

    public function save(){
        $oldGameType = $this->request->param('old_game_type');
        $gameId = $this->request->param('game_id');
        $gameType = $this->request->param('game_type');
        $Active = $this->request->param('isactive_i');
        $showInHall = $this->request->param('showinhall');
        $serverId = $this->request->param('serverID');
        if(empty($serverId)){
            $this->result([],0,'服务器ID不能为空','json',[],'status');
        }
        $web = Db::name('server')->where(['id'=>$serverId])->find();
        if(empty($web)){
            $this->result([],0,'找不到服务器信息','json',[],'status');
        }
        if(empty($gameId) || empty($gameType)){
            $this->result([],0,'游戏信息不完整','json',[],'status');
        }
        $data = $this->request->param();
        $isActive = $Active>0 ? 1 :0;    
		if($showInHall>0){
			$isActive = $isActive|2;			
		}
        $sys = new SystemApi($serverId);
        $model = 'game_type';
        $sData['model'] = $model;
        $sData['where'] = ['game_id'=>$gameId,'game_type'=>$gameType];
        $issetType = $sys->getDbMes('totalQuery', $sData);
        if(!empty($issetType['result']) && (empty($oldGameType) || $oldGameType!=$gameType)){
            $this->result([],0,'已经存在这个类型的房间了','json',[], 'status');
        }
        if(isset($gameId) && strlen($oldGameType)>0){
            // 更新
            $data['game_type'] =  $gameType;
            $data['isactive_i'] = $isActive; 
            $type_data['model'] = $model;
            $type_data['where'] = ['game_id'=>$gameId,'game_type'=>$oldGameType];
            $type_data['data'] = $data;
            $res = $sys->alterDbMes('totalAlter',$type_data);
            $msg = '修改';
        }else{
            //房间不存在则插入			
            $data['isactive_i'] = $isActive;
            $add_data['model'] = $model;
            $add_data['data'] = $data;
            $res = $sys->alterDbMes('totalAdd',$add_data);
            $msg = '添加';
        }
        if($res == 'ok'){
            $this->result([],1,$msg.'成功','json',[], 'status');
        }else{
            $this->result([],0,$msg.'失败','json',[], 'status');
        }
    }

}